#include "helper_hardware.h"

namespace Helper
{

    Hardware::Hardware()
    {
        pinMode(CS_PIN, OUTPUT);
    }

    void Hardware::on()
    {
        digitalWrite(CS_PIN, HIGH);
        sht31.begin(0x44); // 0x44 0x45
    }

    void Hardware::off()
    {
        digitalWrite(CS_PIN, LOW);
    }

    float Hardware::getBatteryPercent()
    {
        // // read adc
        // int adcValue = analogRead(A0);
        // float voltage = adcValue * 1.1 / 4096;
        // voltage = voltage * 2; // r1 / (r1+r2);

        // // calc
        // float batteryPercent = ((voltage - battery_min) / (battery_max - battery_min)) * 100;
        // Serial2.printf("[Battery]: ADC:%d, Vol: %.4f, Pec: %.4f \n", adcValue, voltage, batteryPercent);
        // return batteryPercent;
        adc1_config_width(ADC_WIDTH_12Bit);
        adc1_config_channel_atten(ADC1_CHANNEL_0, ADC_ATTEN_11db);

        //read battery voltage per %
        long sum = 0;                  // sum of samples taken
        float voltage = 0.0;           // calculated voltage
        float output = 0.0;            // output value
        const float battery_max = 3.6; // maximum voltage of battery
        const float battery_min = 3.3; // minimum voltage of battery before shutdown

        float R1 = 100000.0; // resistance of R1 (100K)
        float R2 = 100000.0;  // resistance of R2 (10K)

        for (int i = 0; i < 500; i++)
        {
            sum += adc1_get_voltage(ADC1_CHANNEL_0);
            delayMicroseconds(1000);
        }
        // calculate the voltage
        voltage = sum / (float)500;
        voltage = (voltage * 3.9) / 4096.0; // for internal 1.1v reference
        // use it with divider circuit 
        voltage = voltage / (R2/(R1+R2));
        // round value by two DP
        voltage = roundf(voltage * 100) / 100;
        Serial2.print("voltage: ");
        Serial2.println(voltage, 2);
        float batteryPercent = ((voltage - battery_min) / (battery_max - battery_min)) * 100;
        Serial2.printf("[Battery]: Vol: %.4f, Pec: %.4f \n", voltage, batteryPercent);
        if (batteryPercent < 100)
            return batteryPercent;
        else
            return 100.0f;
    }

    float Hardware::getTemperature()
    {
        float temperature = sht31.readTemperature();
        Serial2.printf("[Temperature]: %.4f\n", temperature);
        return temperature;
    }

    float Hardware::getHumidity()
    {
        float humidity = sht31.readHumidity();
        Serial2.printf("[humidity]: %.4f\n", humidity);
        return humidity;
    }

}